home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: uu4news.netcom.com!zodiac!szh
- From: szh@zcon.com (Syed Zaeem Hosain)
- Subject: Re: Calling a Function Twice from a printf statement.
- Message-ID: <1996Mar5.022348.2491@zcon.com>
- Sender: szh@zcon.com (Syed Zaeem Hosain)
- Nntp-Posting-Host: zodiac
- Reply-To: szh@zcon.com
- Organization: Z Consulting Group
- References: <4he6q9$6r6@newsbf02.news.aol.com>
- Date: Tue, 5 Mar 1996 02:23:48 GMT
-
- In article <4he6q9$6r6@newsbf02.news.aol.com>, razine@aol.com (Razine) writes:
- >I am trying to call a function twice from my program on the same printf
- >line and have run into a small problem. i was wondering if someone can
- >explain how to fix it.
- >
- >
- >void main(void) {
- >
- > printf("First Number is %d , the Second s %d \n",num(0),num(1));
- >
- >}
- >
- >int num(int index) {
- > int return_number;
- >
- > switch(index) {
- > case 0 : return_number=0;
- > case 1 : return_number=1;
- > }
- > return(return_number);
- >}
- >
- >
- >Now with this function, the printf line will display 0 for the first one
- >and garbage for the second one.. I then thought if I made the variable
- >return_number a static variable it would have fixed it but then when i
- >made the change the printf line would give me zero for both of them. Any
- >ideas?
-
- A few potential problems. First, you do not handle the case of when
- 'index' is neither 0 nor 1 - this could result in some uninitialized
- value being returned. And, second, in the switch, the case check for 0
- drops through to the case check for 1 since there is no break.
-
- In this case, the issue of static variables is not important. The
- variable is returned by value.
-
- Finally, to meet ANSI C standards, do declare 'main' as returning int,
- and return a value to the calling OS or program. So, try the following
- instead of what you have (pardon the slight change in style):
-
- zodiac{108}szh: cat foo.c
- #include <stdio.h>
-
- int main(void)
- {
- printf("First Number is %d , the Second is %d \n",num(0),num(1));
- return(0);
- }
-
- int num(int index)
- {
- int return_number; /* You could also initialize here instead of
- using the default in the switch */
- switch(index)
- {
- case 0:
- return_number=0;
- break;
- case 1:
- return_number=1;
- break;
- default:
- return_number=-1;
- }
- return(return_number);
- }
- zodiac{109}szh: gcc -o foo foo.c
- zodiac{110}szh: foo
- First Number is 0 , the Second is 1
- zodiac{111}szh:
-
-
- --
- -------------------------------------------------------------------------
- | Syed Zaeem Hosain P. O. Box 610097 (408) 441-7021 |
- | Z Consulting Group San Jose, CA 95161 szh@zcon.com |
- -------------------------------------------------------------------------
-